import { createRouter, createWebHashHistory } from "vue-router";
import { getAsyncRoutes } from "@/api/routes";
import { initRouter, addAsyncRoutes } from "./utils";
import Layout from "@/layout/index.vue";
import { useRouterStore } from "@/stores/modules/router.ts";
import component from "element-plus/es/components/tree-select/src/tree-select-option.mjs";
//原始静态路由
export const routes: any = [
  {
    path: "/login",
    component: () => import("/src/views/login/index.vue"), // 异步加载的路由的组件位置,只有页面被访问才加载
  },
  {
    path: "/",
    name: "首页",
    component: import('/src/layout/index.vue'),
    redirect: "/welcome",
    meta: { title: "首页" },
    children: [
      {
        //子菜单信息
        path: "/welcome", //路径
        name: "welcome",
        component: () => import("/src/views/welcome/index.vue"), //指定组件
        meta: { title: "首页" },
      },
    ],
  },
  {
    path: "/error",
    redirect: "/error/403",
    meta: {
      icon: "ri:information-line",
      // showLink: false,
      title: "异常页面",
      rank: 9,
    },
    component: Layout,
    children: [
      {
        path: "/error/403",
        name: "403",
        component: () => import("@/views/error/403.vue"),
        meta: {
          title: "403",
        },
      },
      {
        path: "/error/404",
        name: "404",
        component: () => import("@/views/error/404.vue"),
        meta: {
          title: "404",
        },
      },
      {
        path: "/error/500",
        name: "500",
        component: () => import("@/views/error/500.vue"),
        meta: {
          title: "500",
        },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(), // 跳转方式
  routes, // 路由配置
});
//路由白名单 直接放行
const whiteList = ["/login"];

router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.path)) {
    next();
  } else {
    if (sessionStorage.getItem("token")) {
      if (useRouterStore().asyncRouter.length > 0) {
        next();
      } else {
        initRouter().then(() => {
          next({ ...to, replace: true });
        });
      }
    } else {
      router.push("/login");
    }
  }
});

export default router;
